package com.boxedinsoftware.betamax.sms;

import java.io.InputStream;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;



import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class SendSMS extends Activity {
	
	public static final String ADDRESS = "address";
    public static final String PERSON = "person";
    public static final String DATE = "date";
    public static final String READ = "read";
    public static final String STATUS = "status";
    public static final String TYPE = "type";
    public static final String BODY = "body";
    public static final int MESSAGE_TYPE_INBOX = 1;
    public static final int MESSAGE_TYPE_SENT = 2;
	
	
	
	AccountsSQLHelper dh;
	ArrayList<SearchResults> searchResults;
	ListView lv1;
	ArrayList<SearchResults> results;
	String country;
	String text;
	String phone;
	String sCountry;
	String sNumber;
	int count;
	ProgressDialog dialog;
	protected SharedPreferences preferences;
	
		@Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.smshandler);
	        phone = this.getIntent().getStringExtra("number");
	        text = this.getIntent().getStringExtra("message");
	        country = this.getIntent().getStringExtra("country");
	        count = this.getIntent().getIntExtra("count", 1);
	        preferences = PreferenceManager.getDefaultSharedPreferences(this);
	        this.dh = new AccountsSQLHelper(SendSMS.this.getApplicationContext());
	        
	        Button manage = (Button)findViewById(R.id.handler_manage_button);
	        manage.setOnClickListener(new OnClickListener(){

				public void onClick(View arg0) {
					Intent x = new Intent(SendSMS.this, AccountManager.class);
					startActivity(x);
					SendSMS.this.finish();

					
				}
	        	
	        	
	        });
	        
	        lv1 = (ListView)this.findViewById(R.id.handler_list);
	        searchResults = refresh();
	        lv1.setAdapter(new SendSMSBaseAdapter(this, searchResults));
	        lv1.setEmptyView((View)findViewById(android.R.id.empty));
	        
	        get_rates_refresh();
	        
	        
	        lv1.setOnItemClickListener(new OnItemClickListener(){

	        	public void onItemClick(AdapterView<?> a, View v, int position, long id) { 
	  	          Object o = lv1.getItemAtPosition(position);
	  	          SearchResults fullObject = (SearchResults)o;
	  	        if(phone == "")
            	{
            		
            		Toast.makeText(getApplicationContext(), "Failed. No phone number provided.", Toast.LENGTH_LONG).show();
            		
            	}
            	else if(!phone.startsWith("+") && !phone.startsWith("00"))
            	{
            		
            		Toast.makeText(getApplicationContext(), "Failed. Phone number does not contain a country code. Eg. +16642295346 or 0016642295346", Toast.LENGTH_LONG).show();
            		
            	}
            	else if(fullObject.isValid() == false && preferences.getBoolean("denyActive", false) == true)
            	{
            		
            		Toast.makeText(getApplicationContext(), "Insufficient balance. Choose another account or add more credits.", Toast.LENGTH_LONG).show();
            		
            	}
            	else
            	{
            		
            		//String[] params = {fullObject.getProvider() , fullObject.getUsername() , fullObject.getPassword(), phone, sNumber , text};
            		//Toast.makeText(getApplicationContext(), fullObject.getPassword(), Toast.LENGTH_LONG).show();
            		Intent myIntent = new Intent(SendSMS.this, SendSMSService.class);
            	    
            		Bundle bundle = new Bundle();
            		bundle.putString("number", phone);
            		bundle.putString("provider", fullObject.getProvider());
            		bundle.putString("username", fullObject.getUsername());
            		bundle.putString("password", fullObject.getPassword());
            		bundle.putString("text", text);
            		bundle.putInt("count", count);
            		myIntent.putExtras(bundle);
            		//startService(myIntent);    
            		PendingIntent pendingIntent = PendingIntent.getService(SendSMS.this, 0, myIntent, 0);
            		try {
						pendingIntent.send();
					} catch (CanceledException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
            		SendSMS.this.finish();
            		//new SMSsend().execute(params);
            		
            	}
            	
            	
	        	
	        	}
	        });
	        
		}
		
		
		private void get_rates_refresh(){
		     searchResults = new ArrayList<SearchResults>();
		     
		     SearchResults sr1;
		     Cursor cursor = this.dh.selectAllForBalance();
		        while (cursor.moveToNext()) {
		        	sr1 = new SearchResults();
		            sr1.setID(cursor.getInt(0));
		            sr1.setProvider(cursor.getString(1));
		            sr1.setUsername(cursor.getString(2));
		            sr1.setPassword(cursor.getString(3));
		            sr1.setBalance(cursor.getDouble(4));
		            sr1.setCount(count);
		            //Log.e("Betamax", "" + sr1.getAccNumber());
		            SearchResults[] vasile = {sr1};
		            new get_rates().execute(vasile);
		            
		          }
		         
		        cursor.close();
		     
		    }
		
		private ArrayList<SearchResults> refresh(){
		     ArrayList<SearchResults> results = new ArrayList<SearchResults>();
		     
		     SearchResults sr1;
		     Cursor cursor = this.dh.selectAllForBalance();
		        while (cursor.moveToNext()) {
		        	sr1 = new SearchResults();
		            sr1.setID(cursor.getInt(0));
		            sr1.setProvider(cursor.getString(1));
		            sr1.setUsername(cursor.getString(2));
		            sr1.setPassword(cursor.getString(3));
		            sr1.setBalance(cursor.getDouble(4));
		            	results.add(sr1);
		          }
		         
		     return results;
		    }
		
		
		
public class get_rates extends AsyncTask<SearchResults, Void, String> {
	    	
	    	SearchResults[] params;
	    	
	    	@Override
	    	protected String doInBackground(SearchResults... params) {
	    		try{
	        		
	        		this.params = params;
					//Log.e("providerString", providerString);
					
					//Log.e("actualProvider", actualProvider);
	        		 //Log.e("Betamax", this.params[0].getProvider());
				    HttpClient httpclient = new DefaultHttpClient();  
				    HttpGet httpget = new HttpGet("http://www.boxedinsoftware.com/betamax/smsapp/getRates.php?country="+country.replaceAll(" ", "%20")+"&provider="+this.params[0].getProvider());
		            // Add your data  
		           
		      
		            // Execute HTTP Post Request  
		            HttpResponse response = httpclient.execute(httpget);  
		            
		            byte buffer[] = new byte[1024] ;
					InputStream is = response.getEntity().getContent() ;
					int numBytes = is.read(buffer) ;
					is.close();
					
					 String entityContents = new String(buffer,0,numBytes) ;
				    
						

						
			            
					 return entityContents;   
					}      
		         catch (ClientProtocolException e) { 
		        	Log.e("Betamax" , e.getMessage());
		        	return null; 
		        } catch (Exception e) {  
		        	Log.e("Betamax" , e.getMessage());
		        	return null; 
		        }
		        
	    	
	    	
	    	
	 }
	    	
	    	@Override
	    	protected void onPostExecute(String result) {
	    	
	    		if(result == null){
	    			Toast.makeText(SendSMS.this, "Something went wrong. Please check your internet connection", Toast.LENGTH_SHORT).show();
	    			String rate = "-1";
		    		params[0].setSms_rate(Double.parseDouble(rate));
		    		searchResults.add(params[0]);
					lv1.setAdapter(new SendSMSBaseAdapter(SendSMS.this, searchResults));
	    		}
	    		else if(result.startsWith("Unknown"))
	    		{
	    			Toast.makeText(SendSMS.this, "Unable to fetch rates for " + params[0].getProvider(), Toast.LENGTH_SHORT).show();
	    			String rate = "-1";
		    		params[0].setSms_rate(Double.parseDouble(rate));
		    		searchResults.add(params[0]);
					lv1.setAdapter(new SendSMSBaseAdapter(SendSMS.this, searchResults));
	    		}
	    		else{
	    			
		    		try{
		    		params[0].setSms_rate(Double.parseDouble(result));}
		    		catch(Exception e){params[0].setSms_rate(-1);}
		    		
	    		searchResults.add(params[0]);
				lv1.setAdapter(new SendSMSBaseAdapter(SendSMS.this, searchResults));
	    		}
	    	}
	    	
	 }





public static String forHTML(String aText){
    final StringBuilder result = new StringBuilder();
    final StringCharacterIterator iterator = new StringCharacterIterator(aText);
    char character =  iterator.current();
    while (character != CharacterIterator.DONE ){
      if (character == '<') {
        result.append("&lt;");
      }
      else if (character == '>') {
        result.append("&gt;");
      }
      else if (character == '&') {
        result.append("&amp;");
     }
      else if (character == '\"') {
        result.append("&quot;");
      }
      else if (character == '\t') {
        addCharEntity(9, result);
      }
      else if (character == '!') {
        addCharEntity(33, result);
      }
      else if (character == '#') {
        addCharEntity(35, result);
      }
      else if (character == '$') {
        addCharEntity(36, result);
      }
      else if (character == '%') {
        addCharEntity(37, result);
      }
      else if (character == '\'') {
        addCharEntity(39, result);
      }
      else if (character == '(') {
        addCharEntity(40, result);
      }
      else if (character == ')') {
        addCharEntity(41, result);
      }
      else if (character == '*') {
        addCharEntity(42, result);
      }
      else if (character == '+') {
        addCharEntity(43, result);
      }
      else if (character == ',') {
        addCharEntity(44, result);
      }
      else if (character == '-') {
        addCharEntity(45, result);
      }
      else if (character == '.') {
        addCharEntity(46, result);
      }
      else if (character == '/') {
        addCharEntity(47, result);
      }
      else if (character == ':') {
        addCharEntity(58, result);
      }
      else if (character == ';') {
        addCharEntity(59, result);
      }
      else if (character == '=') {
        addCharEntity(61, result);
      }
      else if (character == '?') {
        addCharEntity(63, result);
      }
      else if (character == '@') {
        addCharEntity(64, result);
      }
      else if (character == '[') {
        addCharEntity(91, result);
      }
      else if (character == '\\') {
        addCharEntity(92, result);
      }
      else if (character == ']') {
        addCharEntity(93, result);
      }
      else if (character == '^') {
        addCharEntity(94, result);
      }
      else if (character == '_') {
        addCharEntity(95, result);
      }
      else if (character == '`') {
        addCharEntity(96, result);
      }
      else if (character == '{') {
        addCharEntity(123, result);
      }
      else if (character == '|') {
        addCharEntity(124, result);
      }
      else if (character == '}') {
        addCharEntity(125, result);
      }
      else if (character == '~') {
        addCharEntity(126, result);
      }
      else {
        //the char is not a special one
        //add it to the result as is
        result.append(character);
      }
      character = iterator.next();
    }
    return result.toString();
 }

private static void addCharEntity(Integer aIdx, StringBuilder aBuilder){
    String padding = "";
    if( aIdx <= 9 ){
       padding = "00";
    }
    else if( aIdx <= 99 ){
      padding = "0";
    }
    else {
      //no prefix
    }
    String number = padding + aIdx.toString();
    aBuilder.append("&#" + number + ";");
  }



	/*	//https://www.dialnow.com/myaccount/sendsms.php?username=xxxxxxxxxx&password=xxxxxxxxxx&from=xxxxxxxxxx&to=xxxxxxxxxx&text=xxxxxxxxxx */
}